package com.example.shuiyin.config;

import com.example.shuiyin.constant.Constants;
import com.example.shuiyin.dto.ApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import jakarta.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Configuration
public class SecurityErrorConfig {

    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return (request, response, ex) -> {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(
                    ApiResponse.error(403, Constants.ERROR_ACCESS_DENIED + ": " + ex.getMessage())));
            writer.flush();
        };
    }

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, ex) -> {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(
                    ApiResponse.error(401, Constants.ERROR_AUTHENTICATION_FAILED + ": " + ex.getMessage())));
            writer.flush();
        };
    }
} 